<template>
  <div class="h-full flex-col">
    <SearchForm @handle-reset="resetParams" @handle-search="getList">
      <el-form :model="searchForm" inline>
        <el-form-item label="처리상태">
          <el-select v-model="searchForm.status" placeholder="전체" clearable class="w-200px" @change="getList">
            <el-option label="진행중" :value="0" />
            <el-option label="입금승인" :value="1" />
            <el-option label="입금거절" :value="2" />
            <el-option label="승인취소-성공" :value="3" />
            <el-option label="승인취소-실패" :value="4" />
            <el-option label="전체기록" :value="-1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.depositor_name" placeholder="입금예금주" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.agent_player_name" placeholder="로얄회원ID" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.agent_player_id" placeholder="로얄회원번호" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.phone_number" placeholder="전화번호" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.player_level" placeholder="등급번호" />
        </el-form-item>
      </el-form>
    </SearchForm>

    <el-row v-if="searchForm.status === 0" :gutter="20" style="margin-bottom: 10px">
      <el-col :span="4">
        <el-button type="primary" @click="rechargeApproveAll">일괄승인</el-button>
        <el-button type="warning" @click="rechargeRejectAll">일괄반려</el-button>
      </el-col>
    </el-row>

    <div class="page-card h-full m-table-position" v-loading="loading">
      <div class="m-bet-amount-sum">
        <span>신청금액:</span>
        <el-tag :type="betAmountSum > 0 ? 'danger' : 'success'">
          {{ formatNumber(betAmountSum) }}
        </el-tag>
      </div>

      <MyTable :tableData="tableData" :tableColumn="tableColumn" v-slot="sp">
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
          @sort-change="sortChangeHandle" :highlight-current-row="true">
          <el-table-column v-if="searchForm.status === 0" type="selection" width="55" />
          <el-table-column v-if="sp.ctc.includes('ID')" label="ID" prop="guid" align="center" width="120" />
          <el-table-column v-if="sp.ctc.includes('로얄회원번호')" label="로얄회원번호" prop="agent_player_id" align="center"
            width="120" />
          <el-table-column v-if="sp.ctc.includes('로얄회원ID')" label="로얄회원ID" prop="agent_player_name" align="center"
            width="120" />
          <el-table-column v-if="sp.ctc.includes('등급번호')" label="등급번호" prop="player_level" align="center" width="120" />
          <el-table-column v-if="sp.ctc.includes('등급명')" label="등급명" prop="player_level_name" align="center"
            width="120" />
          <el-table-column v-if="sp.ctc.includes('휴대폰번호')" label="휴대폰번호" prop="phone_number" align="center" width="120" />
          <el-table-column v-if="sp.ctc.includes('입금예금주')" label="입금예금주" prop="depositor_name" align="center"
            width="120" />
          <el-table-column v-if="sp.ctc.includes('입금은행')" label="입금은행" prop="depositor_bank" align="center" width="120" />
          <el-table-column v-if="sp.ctc.includes('신청금액')" label="신청금액" align="center" width="120">
            <template #default="{ row }">
              <el-tag :type="row.amount > 0 ? 'danger' : 'success'">
                {{ formatNumber(row.amount) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('누적배팅금액')" label="누적배팅금액" align="center" width="120">
            <template #default="{ row }">
              <el-tag :type="row.bet_amount > 0 ? 'danger' : 'success'">
                {{ formatNumber(row.bet_amount) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('입금보너스')" label="입금보너스" prop="amount_bonus" align="center" width="120">
            <template #default="{ row }">
              {{ formatNumber(row.amount_bonus) }}
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('입금시잔액')" label="입금시잔액" prop="balance" align="center" width="120"
            sortable>
            <template #default="{ row }">
              {{ formatNumber(row.balance) }}
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('메모')" label="메모" prop="note" align="center" width="300" />
          <el-table-column v-if="sp.ctc.includes('신청시간')" label="신청시간" align="center" width="200" prop="create_ts"
            sortable>
            <template #default="{ row }">
              {{ row.create_ts }}
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('처리시간')" label="처리시간" align="center" width="200">
            <template #default="{ row }">
              {{ row.finish_ts }}
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('처리상태')" label="처리상태" align="center" width="120">
            <template #default="{ row }">
              {{ row.status }}
            </template>
          </el-table-column>
          <el-table-column v-if="sp.ctc.includes('사이트구분')" label="사이트구분" prop="agent_brand" align="center" width="120" />
          <el-table-column v-if="sp.ctc.includes('게임사')" label="게임사" prop="provider_name" align="center" width="120" />
          <el-table-column v-if="sp.ctc.includes('Jade회원번호')" label="Jade회원번호" prop="player_id" align="center"
            width="120" />
          <el-table-column v-if="searchForm.status === 0" label="편집" fixed="right" width="150">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="rechargeEditHandle(row)">승인</el-button>
              <el-button type="warning" size="small" @click="rechargeDeleteHandle(row)">반려</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="searchForm.status === 1" label="편집" fixed="right" width="80" align="center">
            <template #default="{ row }">
              <el-button type="warning" size="small" @click="rechargeRevokeHandle(row)">승인취소</el-button>
            </template>
          </el-table-column>
        </el-table>

        <Pagination :pageable="page" :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange" />
      </MyTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { useTable } from '@/hooks/useTable';
import {
  rechargeListApi,
  rechargeApproveApi,
  rechargeRejectApi,
  rechargeRevokeApi
} from '@/api/financial/index';
import { formatNumber, dataTimeRangeCurTwo, formatDate, timestampToSeoul } from '@/utils/util';
import { ElMessageBox, ElMessage, messageConfig } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { selectGuidMapGet } from '@/utils/gameUtil';
import MyTable from '@/components/MyTable';
import { useMyTip } from '@/hooks/useMyTip';

const mySortArr: any = ref([])

const sortChangeHandle = ({ column, prop, order }) => {
  mySortArr.value = [prop, order];
}
const { operationSuccessMsg } = useMyTip();

const tableColumn = ref([
  'ID',
  '로얄회원번호',
  '로얄회원ID',
  '등급번호',
  '등급명',
  '휴대폰번호',
  '입금예금주',
  '입금은행',
  '신청금액',
  '누적배팅금액',
  '입금보너스',
  '입금시잔액',
  '메모',
  '신청시간',
  '처리시간',
  '처리상태',
  '사이트구분',
  '게임사',
  'Jade회원번호'
]);

const { t } = useI18n();

const rechargeEditHandle = (row: any) => {
  ElMessageBox.confirm(
    `${row.agent_player_name}회원에게${row.amount}원 입금|승인|하시겠습니까?`,
    t('common.mMessageTitle'),
    {
      confirmButtonText: t('common.mConfirmBtn'),
      cancelButtonText: t('common.mCancelBtn'),
      draggable: true
    }
  ).then(() => {
    rechargeApproveApi({ guid: row.guid }).then(({ status }) => {
      tableDataFilter(row.guid);
      if (status == 0) {
        operationSuccessMsg();
      }
    });
  });
};

const rechargeDeleteHandle = (row: any) => {
  ElMessageBox.confirm(`입금을 거절 하시겠습니까?`, t('common.mMessageTitle'), {
    confirmButtonText: t('common.mConfirmBtn'),
    cancelButtonText: t('common.mCancelBtn'),
    draggable: true
  }).then(() => {
    rechargeRejectApi({ guid: row.guid }).then(({ status }) => {
      tableDataFilter(row.guid);
      if (status == 0) {
        operationSuccessMsg();
      }
    });
  });
};

const rechargeRevokeHandle = (row: any) => {
  ElMessageBox.confirm(`입금 승인취소 하시겠습니까?`, t('common.mMessageTitle'), {
    confirmButtonText: t('common.mConfirmBtn'),
    cancelButtonText: t('common.mCancelBtn'),
    draggable: true
  }).then(() => {
    rechargeRevokeApi({ guid: row.guid }).then(({ status }) => {
      tableDataFilter(row.guid);
      if (status == 0) {
        operationSuccessMsg();
      }
    });
  });
};

const rechargeApproveAll = () => {
  const guidArr = selectGuidMapGet(multipleSelection.value);
  ElMessageBox.confirm(`일괄 입금승인 하시겠습니까?`, t('common.mMessageTitle'), {
    confirmButtonText: t('common.mConfirmBtn'),
    cancelButtonText: t('common.mCancelBtn'),
    draggable: true
  }).then(() => {
    let myStatus = 0;
    guidArr.map(async (guid: any) => {
      tableDataFilter(guid);
      const { status } = rechargeApproveApi({ guid });
      if (status != 0) {
        myStatus = status;
      }
    });
    operationSuccessMsg(myStatus);
  });
};

const rechargeRejectAll = () => {
  const guidArr = selectGuidMapGet(multipleSelection.value);
  ElMessageBox.confirm(`일괄 입금반려 하시겠습니까?`, t('common.mMessageTitle'), {
    confirmButtonText: t('common.mConfirmBtn'),
    cancelButtonText: t('common.mCancelBtn'),
    draggable: true
  }).then(() => {
    let myStatus = 0;
    guidArr.map(async (guid: any) => {
      tableDataFilter(guid);
      const { status } = rechargeRejectApi({ guid });
      if (status != 0) {
        myStatus = status;
      }
    });
    operationSuccessMsg(myStatus);
  });
};

const statusMap: any = {
  '0': '진행중',
  '1': '입금승인',
  '2': '입금거절',
  '3': '승인취소-성공',
  '4': '승인취소-실패',
  '-1': '전체기록'
};

const dateTimeRange = dataTimeRangeCurTwo();

const searchForm = reactive({
  agent_player_id: '',
  agent_player_name: '',
  depositor_name: '',
  phone_number: '',
  player_level: '',
  status: 0
});

const multipleSelection = ref([]);

const handleSelectionChange = (val: []) => {
  multipleSelection.value = val;
};

const dataTimeRange: any = ref([]);

onMounted(() => {
  dataTimeRange.value = dateTimeRange.map((item) => new Date(item * 1000));
});

const betAmountSum = ref(0);

const dataCallBack = (data: any) => {
  const _data = data.data;

  let _betAmountSum = 0;

  let list = _data.orders.map((item: any) => {
    _betAmountSum += item.amount;

    item.create_ts = timestampToSeoul(item.create_ts * 1000, 'Y-m-d H:i:s', 1);

    if (Number(item.finish_ts) === 0) {
      item.finish_ts = '';
    } else {
      item.finish_ts = timestampToSeoul(item.finish_ts * 1000, 'Y-m-d H:i:s', 1);
    }

    item.status = statusMap[item.status.toString()];
    return item;
  });

  console.log(mySortArr.value)

  if (mySortArr.value.length > 0) {

    const myProp = mySortArr.value[0]
    const myOrder = mySortArr.value[1]

    if (myProp == 'create_ts') {
      list = list.sort((a: any, b: any) => {
        if (myOrder == 'ascending') {
          return +new Date(a[myProp]) - +new Date(b[myProp]);
        }
        return +new Date(b[myProp]) - +new Date(a[myProp]);
      });
    }
  }

  console.log(list)

  betAmountSum.value = _betAmountSum;

  return {
    list,
    total: _data.total_count
  };
};

const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange, tableDataFilter } =
  useTable({
    apiFn: rechargeListApi,
    params: searchForm,
    callback: dataCallBack,
    reload: 60
  });
</script>

<style lang="scss" scoped>
.m-table-position {
  position: relative;
}

.m-bet-amount-sum {
  position: absolute;
  bottom: 0;
  left: 1.25rem;
  height: 56px;
  width: 300px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}

.m-bet-amount-sum span {
  margin-right: 10px;
}
</style>
